<template>
  <a-modal
      title="文件上传"
      :visible="showModal"
      :footer="null"
      @cancel="showModal = false"
  >
    <div class="clearfix">
      <a-upload
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
          :accept="acceptType"
      >
        <a-button>
          <a-icon type="folder"/>
          选择文件
        </a-button>
      </a-upload>
      <a-button
          type="primary"
          :disabled="fileList.length === 0"
          :loading="uploading"
          style="margin-top: 16px"
          @click="handleUpload"
      >
        {{ uploading ? '上传中' : '开始上传' }}
      </a-button>
    </div>
  </a-modal>
</template>

<script>
import {upload} from "@/utils/request";

export default {
  name: 'FileUploadModal',
  data() {
    return {
      showModal: false,
      fileList: [],
      uploading: false,
    };
  },
  props: {
    url: {
      required: true,
      type: String
    },
    maxCount: {
      required: true,
      type: Number,
      default: 1
    },
    acceptType: {
      required: true,
      type: String,
      default: '*/*'
    }
  },
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      if (this.fileList.length >= this.maxCount) {
        this.$message.error(`最多只能上传 ${this.maxCount} 个文件`)
        return false
      }
      this.fileList = [...this.fileList, file];
      return false;
    },
    handleUpload() {
      const {fileList} = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files', file);
      });

      this.uploading = true;
      upload(this.url, formData)
          .then(res => {
            this.uploading = false;
            this.$message.success(res.msg || '上传成功!');
            this.fileList = []; // 清空已上传文件
            this.showModal = false; // 关闭弹窗
            this.$emit('ok');
          })
          .catch(err => {
            this.uploading = false;
            this.$message.error(err.error || '上传失败!');
          });
    },
  },
};
</script>
